package com.sgcc.nfc.lock.domain.usecase

import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.domain.model.Lock
import com.sgcc.nfc.lock.domain.repository.LockRepository
import javax.inject.Inject

class FindLockByNfcIdUseCase @Inject constructor(
    private val repository: LockRepository
) {

    suspend operator fun invoke(lockNfcId: String): LockAccessResult {
        val response = repository.getLocks(
            page = 1,
            pageSize = DEFAULT_PAGE_SIZE,
            keyword = lockNfcId
        )
        return when (response) {
            is NetworkResult.Success -> {
                val match = response.data.data.firstOrNull { it.lockNfcId.equals(lockNfcId, ignoreCase = true) }
                if (match != null) {
                    LockAccessResult.Allowed(match)
                } else {
                    LockAccessResult.NotFound
                }
            }
            is NetworkResult.Error -> when (response.code) {
                401, 403 -> LockAccessResult.Forbidden(response.message)
                else -> LockAccessResult.Error(response.message)
            }
            NetworkResult.Loading -> LockAccessResult.Error(null)
        }
    }

    sealed class LockAccessResult {
        data class Allowed(val lock: Lock) : LockAccessResult()
        object NotFound : LockAccessResult()
        data class Forbidden(val message: String?) : LockAccessResult()
        data class Error(val message: String?) : LockAccessResult()
    }

    companion object {
        private const val DEFAULT_PAGE_SIZE = 20
    }
}
